/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.archivers.tar.fileEntries;

import com.softwarecraftsmen.archivers.tar.fileEntries.headers.FileHeaderWriter;
import static com.softwarecraftsmen.archivers.tar.fileEntries.headers.FileHeaderWriter.EmptyLinkName;
import static com.softwarecraftsmen.archivers.tar.fileEntries.headers.LinkFlag.NormalFile;
import com.softwarecraftsmen.inputStreamReaders.InputStreamReader;
import com.softwarecraftsmen.inputStreamReaders.ReadableData;
import com.softwarecraftsmen.orogeny.filing.RelativeFile;
import com.softwarecraftsmen.orogeny.filing.absolutePathMetaData.AbsolutePathMetaData;
import static com.softwarecraftsmen.orogeny.filing.fileSystems.PosixCaseSensitiveFileSystem.PosixRoot;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import static java.lang.String.format;
import static java.util.Locale.UK;

public class ReadableDataBackedFileEntry implements FileEntry
{
	private final ReadableData readableData;
	private final AbsolutePathMetaData fileMetaData;
	private final String fileName;

	public ReadableDataBackedFileEntry(final @NotNull ReadableData readableData, final @NotNull RelativeFile fileInTar, final boolean makeAbsolute, final @NotNull AbsolutePathMetaData fileMetaData)
	{
		this.readableData = readableData;
		this.fileMetaData = fileMetaData;
		fileName = makeAbsolute ? fileInTar.makeAbsolute(PosixRoot.root()).toFileSystemSpecificPath() : fileInTar.toFileSystemSpecificPath(PosixRoot);
	}

	public void writeFileHeader(@NotNull final FileHeaderWriter fileHeaderWriter)
	{
		fileHeaderWriter.writeHeader(fileName, fileMetaData, NormalFile, EmptyLinkName);
	}

	@NotNull
	public <T> T readData(final @NotNull InputStreamReader<T> inputStreamReader) throws IOException
	{
		return readableData.readData(inputStreamReader);
	}

	@NotNull
	public String toString()
	{
		return format(UK, "ReadableDataBackedFileEntry(%1$s)", fileName);
	}
}
